<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        class="filter-item"
        placeholder="输入关键字进行过滤"
        v-model="listQuery.keyword"
        style="width: 30%"
      >
      </el-input>
      <!--      <el-input v-model="listQuery.title" placeholder="Title" style="width: 200px;" class="filter-item"-->
      <!--                @keyup.enter.native="handleFilter"-->
      <!--      />-->
      <!--      <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">-->
      <!--        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />-->
      <!--      </el-select>-->
      <!--      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">-->
      <!--        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />-->
      <!--      </el-select>-->
      <!--      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">-->
      <!--        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />-->
      <!--      </el-select>-->
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                 style="margin-left: 10px"
      >
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加管理员
      </el-button>
      <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"-->
      <!--                 @click="handleDownload"-->
      <!--      >-->
      <!--        导出-->
      <!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        审核-->
      <!--      </el-checkbox>-->
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" min-width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="120" align="center" label="头像">
        <template slot-scope="scope">
          <el-avatar shape="square" fit="fit" :src="scope.row.avatar"></el-avatar>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>
      <el-table-column min-width="80" align="center" label="名称">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>
      <el-table-column min-width="180" align="center" label="账号">
        <template slot-scope="scope">
          <span>{{ scope.row.email }}</span>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>
      <el-table-column min-width="80" align="center" label="身份">
        <template slot-scope="scope">
          <span>{{ scope.row.roles_name }}</span>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

      <el-table-column min-width="120" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="120" align="center" label="更新时间">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="180">
        <template slot-scope="scope">
          <el-button type="primary" size="small"  @click="handleCount(scope.row)">
            密钥详情
          </el-button>
          <el-button type="primary" size="small" icon="el-icon-edit" circle @click="handleUpdate(scope.row)">
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" circle @click="del(scope.row.id)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />
    <el-drawer
        :title="'次数详情'+now_title"
        :visible.sync="drawer"
        :with-header="false">
      <el-form ref="dataForm1" :rules="rules" :model="countTemp" label-position="left" label-width="120px"
               style="width: 80%; margin-left:10%;"
      >
        <el-form-item label="回调地址url">
          <el-input v-model="countTemp.api_url"/>
        </el-form-item>
        <el-form-item label="密钥">
          <el-input v-model="countTemp.token"/>
        </el-form-item>
      </el-form>
      <center>
        <el-button type="success" @click="makeToken(countTemp.id)">
          重置密钥
        </el-button>
        <el-button type="primary" @click="editCount">
          保存
        </el-button>
      </center>
    </el-drawer>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="140px"
               style="width: 80%; margin-left:10%;"
      >
        <center>
          <pan-thumb :image="temp.avatar"/>
          <image-cropper
            v-show="imagecropperShow"
            :key="imagecropperKey"
            :width="200"
            :height="200"
            url="/api/upload/base_image"
            lang-type="zh"
            @close="close"
            @crop-upload-success="cropSuccess"
          />
        </center>
        <el-divider>
          <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">
            上传头像
          </el-button>
        </el-divider>
        <br/>
        <el-form-item label="身份" prop="roles_id">
          <el-select v-model="temp.roles_id" filterable placeholder="请选择">
            <el-option label="超级管理员" :value="0">超级管理员</el-option>
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="temp.name"/>
        </el-form-item>
        <el-form-item label="账号" prop="email">
          <el-input v-model="temp.email"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="temp.password" type="password"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="resetForm">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():createData()">
            提交
          </el-button>
        </center>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, create, del, editCount, makeToken} from '@/api/user'
import { all } from '@/api/role'
// import { getMenus } from '@/api/menu'
import Pagination from '@/components/Pagination'
import store from '@/store'
import router from '@/router' // Secondary package based on el-pagination
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'

export default {
  name: 'AdminList',
  components: { Pagination, ImageCropper, PanThumb },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      imagecropperShow: false,
      imagecropperKey: 0,
      menus: [],
      roles: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: '',
        type:'1'
      },
      temp: {
        id: undefined,
        name: '',
        email: '',
        password: '',
        roles_id: '',
        avatar: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_360_360%2F0e%2F8c%2F40%2F0e8c40806fad44e4815f768df67dcb14.jpeg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640851251&t=e6589d08f1d4d9ad125ee07d8b18cb2b'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      countTemp:{
        id:undefined,
        call_count:0,
        call_count_used:0,
        api_url:'',
        call_count_used_month:0,
        token:''
      },
      drawer:false,
      now_title:'',
      rules: {
        name: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
        roles_id: [{ required: true, message: '请选择身份', trigger: 'blur' }],
        email: [{ required: true, message: '请填写账号', trigger: 'blur' }],
        // password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getRoles()
  },
  methods: {
    makeToken(id){
      makeToken(id).then(response => {
        this.countTemp.token =  response.data.token
        // Just to simulate the time of the request
      })
    },
    editCount(){
      editCount(this.countTemp).then(response => {
        this.drawer = false
        if (response.data.code == 200) {
          this.$notify.success({
            title: '成功',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          this.resetTemp()
          this.getList()
        } else {
          this.$notify.error({
            title: '失败',
            message: response.data.msg,
            duration: 2000
          })
        }
      })
    },
    handleCount(row){
      this.drawer = true
      this.now_title = row.name
      this.countTemp.id = row.id
      this.countTemp.call_count = row.call_count
      this.countTemp.call_count_used = row.call_count_used
      this.countTemp.api_url = row.api_url
      this.countTemp.token = row.token
      this.countTemp.call_count_used_month = row.call_count_used_month
    },

    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.temp.avatar = resData.url
    },
    close() {
      this.imagecropperShow = false
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getCheckedNodes() {
      console.log(this.$refs.tree.getCheckedNodes())
    },
    setCheckedNodes(row) {
      this.$refs.tree.setCheckedNodes(row)
    },

    getRoles() {
      all().then(response => {
        this.roles = response.data.data
        // Just to simulate the time of the request
      })
    },
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        console.dir(response)
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    resetForm() {
      this.dialogFormVisible = false
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(response => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            if (response.data.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.resetTemp()
              this.getList()
            } else {
              this.$notify.error({
                title: '失败',
                message: response.data.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp = Object.assign({}, row) // copy obj
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    del(id) {
      this.$confirm('确认要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(response => {
          // this.list.unshift(this.temp)
          if (response.data.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
            const accessRoutes = store.dispatch('permission/generateRoutes', store.getters.token)
            router.addRoutes(accessRoutes)
          } else {
            this.$notify.error({
              title: '失败',
              message: response.data.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        email: '',
        password: '',
        roles_id: '',
        avatar: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_360_360%2F0e%2F8c%2F40%2F0e8c40806fad44e4815f768df67dcb14.jpeg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640851251&t=e6589d08f1d4d9ad125ee07d8b18cb2b'
      }
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
<style scoped>
.avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
}
</style>
